#!/usr/bin/env python
# coding=utf-8

from google.appengine.ext import webapp, db
from v2ex.babel.security import get_current_member
from model.model import PassbyItem
from api import WriteJson
from google.appengine.ext.webapp import util, RequestHandler
from google.appengine.api import memcache
from google.appengine.api.datastore_types import GeoPt
from config import ONE_MONTH

class SendItemHandler(RequestHandler):
    def post(self):
        member = get_current_member(self)
        if member:
            content = self.request.get('content')
            longitude = self.request.get('longitude')
            latitude = self.request.get('latitude')
            if len(content)>0:
                try:
                    template_values = {}
                    item = PassbyItem()
                    item.content = content
                    item.location = GeoPt(float(latitude),float(longitude))
                    item.member = member
                    item.put()
                    memcache.add("PassByItem::"+str(member.key().id), item, ONE_MONTH)
                    template_values["item"] = item
                    WriteJson(self,template_values,'passbyitem.json')
                except:
                    WriteJson(self, {'result':False,'message':'invalid location'}, 'normalResult.json')
            else:
                WriteJson(self, {'result':False,'message':'content can not be null'}, 'normalResult.json')
        else:
            self.redirect("/signin")
            
class GetItemHandler(RequestHandler):
    def get(self):
        id = self.request.get('item_id')
        q = db.GqlQuery('SELECT * FROM LuckyItem WHERE item_id = :1',id)
        if q.count == 1:
            templateData = {}
            templateData['item'] = q[0]
            WriteJson(self,templateData,'luckyItem.json')
        else:
            WriteJson(self, {"result":False,"message":"item not found"}, "normalError.json")
            
class GetItemsByPointHandler(RequestHandler):
    def Get(self):
        #TO-DO
        pass

def main():
    application = webapp.WSGIApplication([('/item/senditem',SendItemHandler),
                                          ('/item/getItem',GetItemHandler),
                                          ('/item/getItemsByPoint',GetItemsByPointHandler),
                                          ('/item/senditem',SendItemHandler)],
                                         debug=True)
    util.run_wsgi_app(application)
        
if __name__ == '__main__':
    main()